# -*- coding:utf-8 -*-
import os
import json
import tkMessageBox
import urllib
from Tkinter import *
from ttk import *

from utils.io_config import Config


class ApkDownloader:
    def __init__(self, action_start, master):
        self.action_start = action_start

        self.index = IntVar()
        self.index.set(0)
        self.is_release = IntVar()

        self.main_frame = Frame(master)
        self.init_ui()

        # keys: doneTime ppServerUrl testApkUrl testMappingUrl releaseApkUrl
        #       releaseMappingUrl gitBranchName versionCode versionName gitTagName
        self.apk_list = []
        self.path = self.get_apk_path()
        self.apk_local = self.get_local_apk()

        self.url_ppcenter = self.get_ppcenter_url()
        self.pageFrom = 0
        self.pageSize = 15
        self.refresh_versions()
        self.refresh_apk_list()

    def init_ui(self):
        self.main_frame.pack(side=TOP, fill=BOTH, expand=True)
        frame_ctrl = Frame(self.main_frame)
        frame_ctrl.pack(side=TOP, expand=False, anchor=W)

        self.cbb_versions = Combobox(frame_ctrl)
        self.cbb_versions["state"] = "readonly"
        self.cbb_versions.bind("<<ComboboxSelected>>", self.select_version)
        self.cbb_versions.pack(side=LEFT, expand=False)

        Button(frame_ctrl, text="上一页", command=self.previous_page).pack(side=LEFT)
        Button(frame_ctrl, text="下一页", command=self.next_page).pack(side=LEFT)
        Button(frame_ctrl, text="下载", command=self.download).pack(side=LEFT)
        Button(frame_ctrl, text="安装", command=self.install).pack(side=LEFT)
        Checkbutton(frame_ctrl, text="release包", variable=self.is_release).pack(side=LEFT)

    def get_ppcenter_url(self):
        """从配置文件中读取url"""
        config = Config()
        url_temp = config.get("url", "ppcenter")
        if len(url_temp) < 5:
            url_temp = "http://100.84.35.78:49000"
        return url_temp

    def next_page(self):
        self.pageFrom += self.pageSize
        self.refresh_apk_list()

    def previous_page(self):
        if self.pageFrom <= 0:
            pass
        else:
            self.pageFrom -= self.pageSize
            self.refresh_apk_list()

    def refresh_apk_list(self):
        """刷新apk列表"""
        "请求apk json列表"
        version_name = self.cbb_versions["values"][self.cbb_versions.current()]
        if version_name == "all":
            version_name = ""
        apk_jsons = urllib.urlopen(self.url_ppcenter +
                                   "/outer/PackageManage/getPackageByVersionName?pageFrom=%s&pageSize=%s&versionName=%s"
                                   # "/ajax/PackController/filterByVersionName?versionName=%s&from=%s&batchCount=%s"
                                   % (str(self.pageFrom), str(self.pageSize), version_name))
        self.apk_list = json.loads(apk_jsons.read())

        "刷新Radiobutton列表"
        if hasattr(self, "frame_apk"):
            self.frame_apk.destroy()
        self.frame_apk = Frame(self.main_frame)
        self.frame_apk.pack(side=TOP, fill=BOTH, expand=True)
        for i in range(len(self.apk_list)):
            apk_info = "\t".join((self.apk_list[i]["versionName"],
                                  self.apk_list[i]["versionCode"],
                                  self.apk_list[i]["gitTagName"]))
            Radiobutton(self.frame_apk,
                        variable=self.index,
                        value=i,
                        text=apk_info
                        ).pack(side=TOP, fill=X, expand=False)

    # def refresh_ui(self):
    #     if hasattr(self, "frame_apk"):
    #         self.frame_apk.destroy()
    #     self.frame_apk = Frame(self.main_frame)
    #     self.frame_apk.pack(side=TOP, fill=BOTH, expand=True)
    #     for i in range(len(self.apk_list)):
    #         apk_info = "\t".join((self.apk_list[i]["versionName"],
    #                               self.apk_list[i]["versionCode"],
    #                               self.apk_list[i]["gitTagName"]))
    #         Radiobutton(self.frame_apk,
    #                     variable=self.index,
    #                     value=i,
    #                     text=apk_info
    #                     ).pack(side=TOP, fill=X, expand=False)

    def download_apk(self):
        if self.is_release.get():
            key_name = "releaseApkUrl"
            apk_mode = "release"
        else:
            key_name = "testApkUrl"
            apk_mode = "debug"
        apk_info = self.apk_list[self.index.get()]
        apk_name = "-".join((apk_info["versionName"],
                             apk_info["versionCode"],
                             apk_info["gitTagName"].split("/")[1],
                             # apk_info["mainTag"].split("/")[1],
                             apk_mode)) + ".apk"
        if apk_name.decode('gbk').encode('utf-8') in self.apk_local:
            print "already exist:", apk_name
        else:
            apk_url = apk_info[key_name]
            print "start to download:", apk_url
            urllib.urlretrieve(apk_url, self.path + apk_name)
            print "download finish:", self.path + apk_name
        return apk_name

    def download(self):
        self.download_apk()
        os.startfile(self.path)

    def install(self):
        apk_name = self.download_apk()
        self.action_start("adb_install", file_path=self.path + apk_name)

    @staticmethod
    def get_apk_path():
        path = Config.get_workspace()  # 从配置文件中读取工作目录
        if len(path) > 1:
            path += "pp\\"
            if not os.path.exists(path):
                os.makedirs(path)
        else:
            path = os.getcwd() + "\\pp\\"
        print "apk download path:", path
        return path

    def get_local_apk(self):
        file_name_list = os.listdir(self.path)
        apk_list = []
        for file_name in file_name_list:
            # path_list.append(file_name.decode('gbk').encode('utf-8'))
            if file_name.endswith(".apk"):
                apk_list.append(file_name.decode('gbk').encode('utf-8'))
        return apk_list

    def get_enable_version(self):
        request = urllib.urlopen(self.url_ppcenter + "/ajax/PackController/listEnabledVersionNames")
        return json.loads(request.read())

    def refresh_versions(self):
        versions = ["all", ] + self.get_enable_version()
        self.cbb_versions["values"] = versions
        self.cbb_versions.current(0)

    def select_version(self, *args):
        self.pageFrom = 0
        self.refresh_apk_list()


class ApkSelector:
    def __init__(self, action_start, master):
        self.action_start = action_start
        """构建apk文件清单"""
        self.master = Frame(master)

        self.path_list = []
        self.path = ""
        self.apk_name = ""

        self.index = IntVar()
        self.index.set(0)
        self.file_var = StringVar()

        self.init_dir()
        self.init_ui()

    def init_dir(self):
        """从配置文件中读取apk目录配置，如无则使用默认的apk目录"""
        config = Config()
        apk_path = config.get_workspace() + "pp"
        if not os.path.exists(apk_path):
            os.makedirs(apk_path)
        self.path_list.append(apk_path)

        path_str = config.get("path", "apk_dir_extend")
        path_str_list = path_str.split(',')
        for path in path_str_list:
            path_clear = path.strip()
            if len(path_clear) > 1:
                try:
                    if os.path.exists(path_clear):
                        self.path_list.append(path_clear)
                except:
                    print "make apk dir fail:", path_clear
        self.path = self.path_list[0]
        print "get apk dir list:", self.path_list

    def init_ui(self):
        frame_ctrl = Frame(self.master)
        frame_ctrl.pack(side=TOP, expand=False, anchor=W)
        Button(frame_ctrl, text="打开目录", command=self.open_dir).pack(side=LEFT)
        Button(frame_ctrl, text="刷新列表", command=self.refresh_apk_list).pack(side=LEFT)
        Button(frame_ctrl, text="安装", command=self.install).pack(side=LEFT)

        self.frame_apk_dir = Frame(self.master)
        self.frame_apk_dir.pack(side=TOP, fill=X, expand=False)
        Label(self.frame_apk_dir, text="APK 目录：").pack(side=LEFT)
        for i in range(len(self.path_list)):
            path = self.path_list[i]
            path = path.replace("\\", "/")
            Radiobutton(self.frame_apk_dir,
                        variable=self.index,
                        value=i,
                        text=path.split("/")[-1],
                        command=self.change_dir
                        ).pack(side=LEFT, fill=X, expand=False, padx=8)

        self.refresh_apk_list()
        lb = Listbox(self.master, listvariable=self.file_var)

        def get_item(event):
            self.apk_name = lb.get(lb.curselection())

        lb.bind('<ButtonRelease-1>', get_item)
        scrl = Scrollbar(self.master)
        scrl.pack(side=RIGHT, fill=Y)
        lb.configure(yscrollcommand=scrl.set)
        lb.pack(side=TOP, fill=BOTH, expand=True)
        scrl['command'] = lb.yview
        self.master.pack(side=TOP, fill=BOTH, expand=True)

    def change_dir(self):
        self.apk_name = ""
        self.path = self.path_list[self.index.get()]
        self.refresh_apk_list()

    def refresh_apk_list(self):
        self.file_var.set(tuple(self.get_file_list()))

    def install(self):
        if self.apk_name == "":
            self.alarm_selection()
        else:
            self.action_start("adb_install", file_path=self.path + "\\" + self.apk_name)

    def get_file_list(self):
        file_name_list = os.listdir(self.path)
        path_list = []
        for file_name in file_name_list:
            # path_list.append(file_name.decode('gbk').encode('utf-8'))
            if file_name.endswith(".apk"):
                path_list.append(file_name.decode('gbk').encode('utf-8'))
        return path_list

    # @staticmethod
    # def get_apk_path():
    #     path = os.getcwd() + "\\apk\\"
    #     if not os.path.exists(path):
    #         os.makedirs(path)
    #     return path

    def open_dir(self):
        os.startfile(self.path)

    @staticmethod
    def alarm_selection():
        tkMessageBox.showwarning("警告", "请选择一个文件！")


class TestToolInstaller:
    def __init__(self, action_start):
        self.action_start = action_start
        self.path = self.get_apk_path()

    @staticmethod
    def get_apk_path():
        path = Config.get_workspace()  # 从配置文件中读取工作目录
        if len(path) > 1:
            path += "apk\\"
            if not os.path.exists(path):
                os.makedirs(path)
        else:
            path = os.getcwd() + "\\apk\\"
        print "testtool download path:", path
        return path

    def get_url_check(self):
        """从配置文件中读取url"""
        config = Config()
        url_temp = config.get("url", "ppcenter")
        if len(url_temp) < 7:
            url_temp = "http://100.84.35.78:49000"
        return url_temp + "/outer/CheckUpdata/checkUpdataTestApk"

    def get_url_update(self):
        url_check = self.get_url_check()
        request = urllib.urlopen(url_check)
        data_temp = json.loads(request.read())
        if "url" in data_temp.keys():
            return data_temp["url"]
        else:
            return ""

    def get_testtool_apk(self):
        url_update = self.get_url_update()
        if len(url_update) > 7:
            apk_name = url_update.split("/")[-1]
            apk_path = self.path + apk_name
            if os.path.exists(apk_path):
                return apk_path
            else:
                print "start to download:", url_update
                urllib.urlretrieve(url_update, apk_path)
                print "download finish:", apk_path
                return apk_path
        return

    def install(self):
        file_path = self.get_testtool_apk()
        self.action_start("adb_install", file_path=file_path)


if __name__ == "__main__":
    root = Tk()
    root.geometry('560x400+300+150')  # 是x 不是*
    "设置窗口是否可调整宽度和高度"
    # root.resizable(width=True, height=True)  # 宽不可变, 高可变,默认为True
    "设置窗口标题"
    root.title("Apk Downloader")

    from AdbManager import AdbManager
    adb = AdbManager("com.pp.assistant")
    var_batch = BooleanVar()  # 必须初始化Tk()后才能初始化IntVar()等
    var_batch.set(False)
    frame_main = Frame(root)
    frame_main.pack(side=TOP, fill=BOTH, expand=True)
    # installer = ApkDownloader(frame_main, adb, var_batch)

    def send_action(self, action, is_batch=False, **kwargs):
        self.adb.receive_action(action, is_batch, **kwargs)

    installer = ApkSelector(send_action, frame_main)

    root.mainloop()
